package com.heking.speechapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.heking.speech.SpeechDialogCreator;
import com.heking.speech.core.SpeechDialogListener;
import com.heking.speech.core.SpeechError;
import com.heking.speech.xunfei.XunFeiSpeechDialogWrap;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_CODE=1231;
    private Button mBtn1;
    private TextView mTvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();
        addListener();
    }

    private void findViews() {
        mBtn1 = findViewById(R.id.btn1);
        mTvResult = findViewById(R.id.tv_result);
    }

    private void addListener(){
        mBtn1.setOnClickListener(v->{
            if(ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)!= PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.RECORD_AUDIO},REQUEST_CODE);
            }else{
                showSpeechDialog();
            }


        });
    }

    private void showSpeechDialog(){
        XunFeiSpeechDialogWrap xunFeiSelfDialog = SpeechDialogCreator.createXunFeiSelfDialog(this);
        xunFeiSelfDialog.setListener(new SpeechDialogListener() {
            @Override
            public void onResult(String result) {
                mTvResult.setText(result);
            }

            @Override
            public void onError(SpeechError speechError) {
                mTvResult.setText(speechError.toString());

            }
        });
        xunFeiSelfDialog.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==REQUEST_CODE){
            boolean success=true;
            for (int i = 0; i < grantResults.length; i++) {
                if(PackageManager.PERMISSION_GRANTED != grantResults[i]){
                    success=false;
                    break;
                }
            }
            if(success){
                showSpeechDialog();
            }else{
                Toast.makeText(this, "缺少录音权限", Toast.LENGTH_SHORT).show();
            }

        }


    }
}